/*
 * @Description:
 * @Version: 2.0
 * @Autor: huangfu
 * @Date: 2020-09-14 16:21:22
 * @LastEditors: 大司马
 * @LastEditTime: 2021-01-06 14:46:27
 */
import axios from 'axios'
import store from '@/store'
import config from '@/config'
import platform from '@/config/platform'
import qs from 'qs'
import {
    getToken
} from '@/libs/util'
import router from '@/router'
import ViewUI from 'view-design';
import { platformLogout } from '@/libs/login'
import { refreshLogOut } from '@/libs/tools'
import baseURL from './baseURL'
import Cookie from 'js-cookie'
class HttpRequest {
    /**
     * 定义实例参数
     */
    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
        this.queue = {}
        this.timer = null
        this.refreshTime = null
    }

    /**
     * 请求参数配置
     */
    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl
        }
        return config
    }
    destroy(url) {
            delete this.queue[url]
        }
        // 静默（不操作）20分钟后退出
    refreshLogOut(res) {
            refreshLogOut(() => {}, res);
            // clearTimeout(this.refreshTime)
            // this.refreshTime = setTimeout(() => {
            //     alert('长时间不操作，自动退出');
            //     platformLogout()
            // }, 1200000);
        }
        /**
         * 拦截器
         */
    interceptors(instance, url) {
        const { mainUserId, id: userId } = store.state.user.userInfo
        instance.interceptors.request.use(config => {
            const { state } = store
            if (getToken()) {
                config.headers['user-id'] = state.user.userInfo.id
                config.headers['main-user-id'] = state.user.userInfo.mainUserId
                config.headers['Authorization'] = getToken()
            } else {
                delete config.headers['Authorization']
            }
            return config
        }, error => {
            return Promise.reject(error)
        })

        instance.interceptors.response.use(res => {
            // 静默（不操作）20分钟后退出
            this.refreshLogOut(res)
                // ....
            const { errorcode, msg, ret } = res.data
            if (ret === 0) {
                return Promise.resolve(res.data)
            } else {
                if (!errorcode) {
                    return Promise.resolve(res)
                }
                if ([401, 500].includes(errorcode) && msg.match(RegExp(/Subject does not have permission/))) {
                    ViewUI.Message.warning('无使用权限，请联系管理员处理')
                    return Promise.reject({ message: '无使用权限，请联系管理员处理' })
                } else if ([401, 2002].includes(errorcode)) {
                    console.log(JSON.stringify(res), '-跳转统一登陆页面')
                    platformLogout()
                }
                return Promise.reject(res.data)
            }
        }, error => {
            clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                ViewUI.Message.warning('服务器状态异常')
            }, 500)
            return Promise.reject(error)
        })
    }

    /**
     * 请求对象
     * @param {object} options 请求配置
     * @param {boolean} muck 是否开启模拟数据
     *
     */
    request(options, muck = false) {
        if (muck) this.baseUrl = config.baseUrl.muck
        if (options.method === 'get') {
            options.paramsSerializer = function(params) {
                return qs.stringify(params, { arrayFormat: 'repeat' })
            }
        }
        const instance = axios.create({
                timeout: options.timeout || 1000 * 10
            })
            // 如果默认不包含baseURL,则获取baseURL
        if (!options.baseURL) {
            options = Object.assign(this.getInsideConfig(), options)
        }
        this.interceptors(instance, options.url)
        return instance(options)
    }
}
export default HttpRequest